package com.example.mptnet;

import android.app.TimePickerDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.mptnet.Interfaces.API;
import com.example.mptnet.Models.Group;
import com.example.mptnet.Models.Mailing;
import com.example.mptnet.Models.User;
import com.example.mptnet.Models.Users_info;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.stream.Collectors;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class Settings extends Fragment {
    Retrofit retrofit;
    API api;
    SharedPreferences settings;
    Mailing mailing = new Mailing();
    String UID = "";
    EditText edittext;
    User user = new User();
    ArrayList<Group> groups = new ArrayList<>();
    ArrayList<Users_info> users_info = new ArrayList<>();
    AutoCompleteTextView textview;
    EditText login, password;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.fragment_settings, container, false);
        retrofit = Builder.request();
        api = retrofit.create(API.class);
        edittext = ((EditText)view.findViewById(R.id.newtime));
        textview = view.findViewById(R.id.groups);
        login = view.findViewById(R.id.login);
        password = view.findViewById(R.id.password);
        settings = getContext().getApplicationContext().getSharedPreferences("SETTINGS", Context.MODE_PRIVATE);
        view.findViewById(R.id.timebutton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        edittext.setText(hourOfDay + ":"+minute+":00");
                    }
                };
                LocalTime time = LocalTime.now();
                TimePickerDialog timePickerDialog = new TimePickerDialog(getContext(),timeSetListener,time.getHour(),time.getMinute(),true);
                timePickerDialog.show();
            }
        });
        UID = settings.getString("UID", "");
        Call<User> calluser = api.GetUser(UID);
        calluser.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if(response.isSuccessful()){
                    user = response.body();
                    textview.setText(user.getUsers_group());
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
        Call<Mailing> callmailing = api.GetMailing(UID);
        callmailing.enqueue(new Callback<Mailing>() {
            @Override
            public void onResponse(Call<Mailing> call, Response<Mailing> response) {
                if(response.isSuccessful()) {
                    mailing = response.body();
                    edittext.setText(mailing.getTime());
                }
            }

            @Override
            public void onFailure(Call<Mailing> call, Throwable t) {
                Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
        Call<ArrayList<Group>> callgroups = api.GetGroups();
        callgroups.enqueue(new Callback<ArrayList<Group>>() {
            @Override
            public void onResponse(Call<ArrayList<Group>> call, Response<ArrayList<Group>> response) {
                if(response.isSuccessful()){
                    groups = response.body();
                    ArrayList<String> list_string = new ArrayList<>();
                    for (int i = 0; i < groups.size(); i++) {
                        list_string.add(groups.get(i).getTitle());
                    }
                    ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), androidx.appcompat.R.layout.support_simple_spinner_dropdown_item, list_string);
                    textview.setAdapter(adapter);
                }
            }

            @Override
            public void onFailure(Call<ArrayList<Group>> call, Throwable t) {
                Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
        Call<ArrayList<Users_info>> callusersinfo = api.GetInfo();
        callusersinfo.enqueue(new Callback<ArrayList<Users_info>>() {
            @Override
            public void onResponse(Call<ArrayList<Users_info>> call, Response<ArrayList<Users_info>> response) {
                if(response.isSuccessful()){
                    users_info = response.body();
                    for (int i = 0; i < users_info.size(); i++) {
                        if(users_info.get(i).getUser_id().equals(UID)){
                            password.setText(users_info.get(i).getPassword());
                            login.setText(users_info.get(i).getLogin());
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<ArrayList<Users_info>> call, Throwable t) {
                Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
        view.findViewById(R.id.saveupdate).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(edittext.getText().equals("")) {
                    Toast.makeText(getContext(), "Нужно заполнить время для расписаний", Toast.LENGTH_LONG).show();
                    return;
                }
                else if(!edittext.getText().equals("") && textview.getText().equals("")){
                    Toast.makeText(getContext(), "Нужно указать группу для расписания", Toast.LENGTH_LONG).show();
                    return;
                }
               else if(login.getText().equals("") || password.getText().equals("") || edittext.getText().equals("") || textview.getText().equals("")){
                    Toast.makeText(getContext(), "Не все поля заполнены", Toast.LENGTH_LONG).show();
                    return;
                }
               else if(!groups.stream().map(i -> i.getTitle()).collect(Collectors.toList()).contains(textview.getText().toString())){
                    Toast.makeText(getContext(), "Такой группы не обнаружено", Toast.LENGTH_LONG).show();
                    return;
                }
               else if(!isValidTimeFormat(edittext.getText().toString())){
                    Toast.makeText(getContext(), "Вы что-то не то намутили с временем", Toast.LENGTH_LONG).show();
                    return;
                }
               else {
                   Call<ResponseBody> updatecall = api.updateInfo(UID, login.getText().toString(), password.getText().toString(), textview.getText().toString(), edittext.getText().toString());
                    updatecall.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            if(response.isSuccessful()){
                                Toast.makeText(getContext(),"Обновление данных успешно выполнено", Toast.LENGTH_LONG).show();
                                getFragmentManager().beginTransaction().replace(R.id.fragment_container, new Profile()).commit();
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {
                            Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        });
        return view;
    }

    public static boolean isValidTimeFormat(String timeString) {
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
            LocalTime.parse(timeString, formatter);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}